﻿<%@ WebHandler Language="C#" Class="MapInit" %>

using System;
using System.Collections;
using System.Web;

using monadsphere;
using monadsphere.ashx;
using monadsphere.js;
using monadsphere.browser;
using monadsphere.dom.html2;

public class MapInit : JSHandler {

    public override void process(HttpContext context, Hashtable data) {
        HtmlWindow.alert("time:", DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss"));

        System.Threading.Thread.Sleep(10000);
        
        HTMLDocument doc = HTMLDocument.instance;
        HTMLDivElement map_div = doc.createElement<HTMLDivElement>();
        map_div.style.width = "500px";
        map_div.style.height = "300px";
        HTMLDocument.instance.body.appendChild(map_div);
        
        function initialize = delegate {
            JSStmt.IF(google.maps.BrowserIsCompatible(), () => {
                google.maps.Map2 map = new google.maps.Map2(map_div, null);
                map.setCenter(new google.maps.LatLng(37.4419, -122.1419, false), 13);
                map.setUIToDefault();

                google.maps.LatLngBounds bounds = map.getBounds();
                google.maps.LatLng southWest = bounds.getSouthWest();
                google.maps.LatLng northEast = bounds.getNorthEast();
                JSNumber lng = southWest.lng();
                JSNumber lat = southWest.lat();
                JSNumber lngSpan = northEast.lng() - lng;
                JSNumber latSpan = northEast.lat() - lat;

                JSNumber iter = new JSNumber(0);
                
                JSStmt.FOR(iter < 9, () => {
                    google.maps.LatLng point = new google.maps.LatLng(lat + latSpan * JSMath.random(), lng + lngSpan * JSMath.random());
                    map.addOverlay(new google.maps.Marker(point));
                    iter++;
                });

                map.openInfoWindow(map.getCenter(),
                   doc.createTextNode("Hello!"));

                function click = delegate {
                    HtmlWindow.alert("You clicked the map.");
                };

                google.maps.Event.addListener(map, "click", click);
                function unload = delegate {
                    google.maps.Unload();
                };

                HtmlWindow.onunload = unload;
            });
        };
        
        function callback = delegate {
            google.load("maps", "2", new OptionalSettings {
                callback = initialize
            });
        };

        google.initLoader("ABQIAAAA10ujn-ZyVk6I1B8m6jIu_xT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSAFtB27Q0EkW6twJksbsBFY2PsvQ", new JSFunction("initLoader", callback));
        HtmlWindow.alert("time:", DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss"));
    }
}
